import React, {PropTypes} from "react";
import {connect} from "react-redux";
import {Link} from "react-router";
import cookie from "react-cookie";
import CommonTitle from "../../components/CommonTitle";
import OrderGoods from "../../components/OrderGoods";
import { fetchPosts,reset } from '../../actions';


class orderConfirm extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: true,
            isShow: false,
            shoppingItemList: [],
            isFromShoppingCar: 0,
            amount: 0,
            discountAmount: 0,
            tradeType: 0,
            goodsList:[],
            isPost: false,
        }
    }
    componentWillMount() {
        document.title="填写订单";
    }
    componentDidMount() {
        const isFromShoppingCar = this.props.location.query.isFromShoppingCar;
        this.setState({isFromShoppingCar: isFromShoppingCar});
        let shoppingItemList = [];
        if(isFromShoppingCar == 0) {
            shoppingItemList = cookie.load("shoppingItemList") || [];
        } else {
            const shoppingCarItemList = cookie.load("shoppingCarItemList") || [];
            shoppingCarItemList.map((item)=>{
                if(item.isChecked) {
                    shoppingItemList.push(item);
                }
            })
        }
        //cookie.remove("shoppingItemList");
        this.setState({shoppingItemList: shoppingItemList});

        let amount = 0;
        let bazaarPriceAmount = 0;
        let goodsList = [];
        let tradeType = 0;
        shoppingItemList.map((item)=>{
            amount += (item.price * item.buyNumber);
            bazaarPriceAmount += (item.bazaarPrice * item.buyNumber)
            if((tradeType == 0) && (item.tradeType == 1)) {
                tradeType = 1;
            }
            goodsList.push({buyNumber:item.buyNumber, categoryCode:item.categoryCode, goodsNo:item.goodsNo, specificationNo:item.specificationNo});
        })
        this.setState({amount: amount, discountAmount: (bazaarPriceAmount - amount).toFixed(2), goodsList:goodsList, tradeType:tradeType});
    }

    componentWillReceiveProps(nextProps) {
        if(nextProps.OrderInfo.errorCode == 0) {
            cookie.remove("user_address");
            cookie.remove("shoppingItemList");
            cookie.remove("isOrder");
            const shoppingCarItemList = cookie.load("shoppingCarItemList") || [];
            let unShoppingItemList = [];
            shoppingCarItemList.map((item)=>{
                if(!item.isChecked){
                    unShoppingItemList.push(item);
                }
            })
            cookie.remove("shoppingCarItemList");
            if(unShoppingItemList.length > 0) {
                cookie.save("shoppingCarItemList", unShoppingItemList);
            }

            alert("提交成功");
            // this.context.router.push("/mall/orderPay?orderId=" + nextProps.OrderInfo.data.orderId);
            window.location.href = "http://weixin.hzyisu.com/orderPay.html?orderId=" + nextProps.OrderInfo.data.orderId;
        } else if(nextProps.OrderInfo.errorCode && nextProps.OrderInfo.errorCode != 0){
            alert("提交失败");
            this.setState({isPost: false});
        }
    }

    postOrder() {
        const address = cookie.load("user_address");
        if (!address) {
            alert("请添加收货地址！");
            return;
        }
        if (this.state.tradeType === 1 && (!address.userIdNumber || (address.userIdNumber == ""))) {
            alert("您所购买商品为境外商品，请在地址中添加身份信息，否则货物将无法发出。");
            return;
        }
        if(!this.state.isPost) {
            const header = {"X-Client-ID": '123456', "X-Long-Token": cookie.load("token")};
            const orderParams = {
                consigneeAccount: address.consigneePhone,
                consigneeAddress: address.address,
                consigneeArea: address.area,
                consigneeCity: address.city,
                consigneeIdNumber: address.userIdNumber,
                consigneeName: address.consigneeName,
                consigneeProvince: address.province,
                orderGoodsRequestVos: this.state.goodsList
            };
            this.props.dispatch(fetchPosts("saveOrder", header, orderParams));
            this.setState({isPost: true});
        }
    }

    renderDiscount() {
        if(this.state.discountAmount > 0) {
            return(
                <div className="order-discount">
                    <div>{this.state.discountAmount}元</div>
                </div>
            )
        }
    }

    renderAddress() {
        const address = cookie.load("user_address");
        if(address) {
            return(
                <div className="order-address-info2">
                    <ul>
                        <li>
                            <Link onClick={this.selectAddress.bind(this)}>
                                <div className="order-address-box">
                                    <div className="address-info">
                                        <div className="address-name">{address.consigneeName}</div>
                                        <div className="address-tel">
                                            {address.consigneePhone}
                                            <i>{address.province}{address.city}{address.area}{address.address}</i>
                                        </div>
                                    </div>
                                </div>
                            </Link>
                        </li>
                    </ul>
                </div>
            );
        } else {
            return (
                <div className="order-address-info">
                    <ul>
                        <li>
                            <Link onClick={this.selectAddress.bind(this)}>请添加收货地址</Link>
                        </li>
                    </ul>
                </div>
            );
        }
    }

    selectAddress() {
        cookie.save("isOrder", 1);
        this.context.router.push("/mall/addressList");
        event.preventDefault();
    }

    render() {
        return(
            <div>
                {this.renderAddress()}

                <div>
                    {this.state.shoppingItemList.map((item, index)=>{
                        return(
                             <OrderGoods key={item.goodsNo} item={item} index={index}/>
                        )
                    })
                    }
                </div>
                {this.renderDiscount()}

                <div className="order-confirm-bottom">
                    <ul>
                        <li className="order-amount">
                            <div>实付款:¥{this.state.amount}</div>
                        </li>
                        <li className="order-button">
                            <Link onClick={this.postOrder.bind(this)}>
                                下单
                            </Link>
                        </li>
                    </ul>
                </div>
            </div>
        )
    }

}

orderConfirm.propTypes = {
    isFetching: PropTypes.bool.isRequired,
    dispatch: PropTypes.func.isRequired
}
orderConfirm.contextTypes = {
    router:React.PropTypes.object
}

function mapStateToProps(state){
    const { postsByApi } = state
    const {
        isFetching,
        items: GoodsInfo
    } = postsByApi["goodsDetail"] || {
        isFetching: false,
        items: {}
    }
    const {
        items: Config
    } = postsByApi["goodsConfig"] || {
        items: {}
    }
    const {
        items: OrderInfo
    } = postsByApi["saveOrder"] || {
        items: {}
    }
    return {
        GoodsInfo,
        Config,
        OrderInfo,
        isFetching
    }
}


export default connect(mapStateToProps)(orderConfirm);

